<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Message;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use App\Models\Member;
use App\Models\MemberAddress;
use Log;

class MemberController extends Controller
{

    /**
     * @api {get} /member/login
     * 会员登陆
     */
    public function login(Request $request)
    {
         $rules = [
            'username'          => 'required|string',
            'password'          => 'required|string',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        //查询用户
        $member = Member::where('username', trim($this->validated['username']))->first();

        //校验用户是否存在，不存在则创建新用户
        if(!$member)
        {
            // self::clear();
            // $request->session()->flush();

            return $this->output(200500, '', '用户不存在');
        }

        $checkPassword = crypt($this->validated['password'],  $member->password);

        // 验证密码
        if ($checkPassword != $member->password)
        {
            return $this->output(200500, '', '密码错误');
        }

        $result = Member::login($member->toArray());

        return $this->output(200, $result);
    }

     /**
     * @api {post} /member/getOpenId
     * 前端登陆
     */
    public function getOpenId(Request $request)
    {
        $rules = [
            'js_code'        => 'required',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $app = Factory::miniProgram($this->config);

        $res = $app->auth->session($this->validated['js_code']);

        Log::info('wechat_login_res:'.json_encode($res));

        if(isset($res['errcode']) && $res['errcode'])
        {
            return $this->output(200602, [], $res['errmsg']);
        }

        $member =  \Auth::guard('member')->user();

        $member_id = $member->member_id;

        // 检测openid是否存在 不存在则创建用户
        $info = Member::where('openid', $res['openid'])->where('member_id', $member_id)->first();

        if (isset($res['openid']) && !$info)
        {
            $member_info = [
                'openid' => $res['openid'],
                'updated_at' => date('Y-m-d H:i:s'),
            ];

            $r = Member::where('member_id', $member_id)->update($member_info);
            if (!$r)
            {
                return $this->output(200602, $r, '更新openid失败');
            }
        }

        return $this->output(200, $res);
    }

    /**
     * @api {post} /member/logout
     * 会员退出
     */
    public function logout(Request $request)
    {
        $res = Member::logout();

        if (!$res)
        {
            return $this->output(200500, '', '退出失败');
        }

        return $this->output(200, $res);
    }

    /**
     * @api {post} /member/update
     * 更新会员信息
     */
    public function update(Request $request)
    {

        $rules = [
            'name'              => '',
            'mobile'            => '',
            'email'             => '',
            'committees'        => '',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $data = Member::setMemberInfo($this->validated);

        return $this->output(200, $data);
    }

    /**
     * @api {post} /member/address
     * 会员收货地址列表
     */
    public function memberAddress(Request $request)
    {
        $rules = [
            'page'            => 'integer|min:1',
            'per_page'        => 'required_with:page|integer|min:1',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $member =  \Auth::guard('member')->user();

        $this->validated['member_id'] = $member->member_id;

        $data = MemberAddress::getList($this->validated);

        return $this->output(200, $data);
    }

    /**
     * @api {post} /member/saveAddress
     * 新增/编辑收货地址
     */
    public function saveAddress(Request $request)
    {
        $rules = [
            'consignee'             => 'required|string',
            'mobile'                => 'required|string',
            'province'              => 'required|string',
            'city'                  => 'required|string',
            'district'              => 'required|string',
            'address'               => 'required|string',
            'default'               => 'integer|min:0',
            'id'                    => 'integer|min:1',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $member =  \Auth::guard('member')->user();

        $this->validated['member_id'] = $member->member_id;

        $msg = '';
        $data = MemberAddress::updateOrCreateAddress($this->validated, $msg);

        if (!$data)
        {
            return $this->output(200500, '', $msg);
        }

        return $this->output(200, $data);
    }

    /**
     * @api {post} /member/deleteAddress
     * 删除收货地址
     */
    public function deleteAddress(Request $request)
    {
        $rules = [
            'id'                    => 'integer|min:1',
        ];

        if ($error = $this->validateInput($rules)) {
            return $error;
        }

        $member =  \Auth::guard('member')->user();

        $this->validated['member_id'] = $member->member_id;

        $msg = '';
        $data = MemberAddress::deleteAddress($this->validated, $msg);

        if (!$data)
        {
            return $this->output(200500, '', $msg);
        }

        return $this->output(200, $data);
    }



}
